package com.tech.cloudapp.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware {

	/** Spring应用上下文环境 */

	private static ApplicationContext applicationContext;


	public static AutowireCapableBeanFactory getAutowireCapableBeanFactory()
	{
		ApplicationContext context = SpringUtils.getContext();
		return context.getAutowireCapableBeanFactory();
	}


	public static ApplicationContext getContext() {
		return applicationContext == null ? null : applicationContext;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringUtils.applicationContext = applicationContext;
	}

	public static void set(ApplicationContext applicationContext)
	{
		SpringUtils.applicationContext = applicationContext;
	}

	/**
	 * 获取对象
	 *
	 * @param beanName
	 * @return Object 一个以所给名字注册的bean的实例
	 * @throws BeansException
	 *
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName) throws BeansException
	{
		return (T) applicationContext.getBean(beanName);
	}





}
